﻿using B.S.BaseData.ErrorCode;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.ReportlossesModelCommand;
using B.S.BaseData.Manage.Api.Read.Apilaction.Command.StoreCommand;
using B.S.BaseData.Manage.Api.Read.DTO;
using DAL;
using MediatR;

namespace B.S.BaseData.Manage.Api.Read.Apilaction.CoomandHandler.ReportlossesModelCommandHandler
{    /// <summary>
     /// 报损管理分页查询
     /// </summary>
    public class ReportlossesQuserModelCommandHandler : IRequestHandler<ReportlossesQuserModelCommand, ApiReqult<ApIPageing<ReportlossesModelDTO>>>
    {
        private readonly DBHelper bHelper;

        public ReportlossesQuserModelCommandHandler(DBHelper bHelper)
        {
            this.bHelper = bHelper;
        }
        /// <summary>
        /// 报损管理分页查询
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public async Task<ApiReqult<ApIPageing<ReportlossesModelDTO>>> Handle(ReportlossesQuserModelCommand request, CancellationToken cancellationToken)
        {
            var result = new ApiReqult<ApIPageing<ReportlossesModelDTO>>();
            result.Code = ApiEnum.查询成功;
            result.Msg = ApiEnum.查询成功.ToString();

            var list = $"SELECT * FROM (SELECT mm.* FROM ReportlossesModel mm ORDER BY mm.Id DESC OFFSET (({request.PageIdex}-1)*{request.PageSize}) ROWS FETCH NEXT {request.PageSize} ROWS ONLY) as temp WHERE IsDelete = 0";
            if (!string.IsNullOrEmpty(request.Lossreportnumber))
            {
                list += $" and Lossreportnumber = '{request.Lossreportnumber}'";
            }
            if (!string.IsNullOrEmpty(request.Thetypeoflossreport))
            {
                list += $" and Thetypeoflossreport = '{request.Thetypeoflossreport}'";
            }
            if (request.Reviewstatus != null)
            {
                // 假设 Storage 是 int 类型，去掉单引号
                list += $" and Reviewstatus = {request.Reviewstatus}";
            }

            var sql = "SELECT COUNT(*) FROM ReportlossesModel";

            ApIPageing<ReportlossesModelDTO> apiPaging = new ApIPageing<ReportlossesModelDTO>();
            apiPaging.TotalCount = (int)bHelper.Scalar(sql);
            apiPaging.TotalPage = (int)Math.Ceiling(apiPaging.TotalCount * 1.0 / request.PageSize);

            apiPaging.List = bHelper.GetList<ReportlossesModelDTO>(list);
            result.Data = apiPaging;

            return result;
        }
    }
}
